<?php
// +----------------------------------------------------------------------
// | guoliduo
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://www.guoliduo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Csh <1317841280@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\model\NodeModel;

class Node extends Base
{
    // 节点列表
    public function index()
    {
        $node = new NodeModel();
        $nodes = $node->getNodeList();
        // 拼装参数
        foreach($nodes as $key=>$vo){
            $nodes[$key]['operate'] = $this->makeButton($vo);
        }
        $nodes = getTree(objToArray($nodes), false);
        if(request()->isAjax()){
            return json(msg(1, $nodes, 'ok'));
        }
        $this->assign([
            'nodes' => $nodes,
            't' => input('t')?:'0',
            'c' => input('c')?:'0'
        ]);
        return $this->fetch();
    }

    // 添加节点
    public function nodeAdd()
    {
        $param = input('post.');
        if(empty($param['node_name'])){
            return json(msg(2, '', '菜单名不能为空！'));
        }
        if(empty($param['mca'])){
            return json(msg(3, '', '路径不能为空！'));
        }

        $node = new NodeModel();
        $flag = $node->insertNode($param);

        return json(msg($flag['code'], $param['type_id'], $flag['msg']));
    }

    // 编辑节点
    public function nodeEdit()
    {
        $param = input('post.');
        if(empty($param['node_name'])){
            return json(msg(2, '', '菜单名不能为空！'));
        }
        if(empty($param['mca'])){
            return json(msg(3, '', '路径不能为空！'));
        }

        $node = new NodeModel();
        $flag = $node->editNode($param);
        return json(msg($flag['code'], 0, $flag['msg']));
    }

    // 删除节点
    public function nodeDel()
    {
        $id = input('param.id');

        $role = new NodeModel();
        $flag = $role->delNode($id);
        return json(msg($flag['code'], $flag['data'], $flag['msg']));
    }

    /**
     * 拼装操作按钮
     * @param $item
     * @return string
     */
    private function makeButton($item)
    {
        return showOperate([
            '编辑' => [
                'auth' => 'user/useredit',
                'href' => "javascript:edit(" . $item['id'] .",'".$item['name']."','".$item['mca']."')",
                'btnStyle' => 'primary'
            ],
            '删除' => [
                'auth' => 'user/userdel',
                'href' => "javascript:delNode(" . $item['id'] .")",
                'btnStyle' => 'danger'
            ]
        ]);
    }
}